package com.biostime.qdingding.modules.qd.service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.biostime.qdingding.common.persistence.Page;
import com.biostime.qdingding.common.service.CrudService;
import com.biostime.qdingding.common.utils.DateUtils;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.modules.qd.api.dto.BalanceDto;
import com.biostime.qdingding.modules.qd.api.dto.ContractDto;
import com.biostime.qdingding.modules.qd.dao.ContractDao;
import com.biostime.qdingding.modules.qd.entity.Center;
import com.biostime.qdingding.modules.qd.entity.Contract;
import com.biostime.qdingding.modules.qd.entity.Member;
import com.biostime.qdingding.modules.qd.entity.Membercenter;
import com.biostime.qdingding.modules.qd.entity.Memberstudent;
import com.biostime.qdingding.modules.qd.entity.Privilege;
import com.biostime.qdingding.modules.qd.entity.Student;
import com.biostime.qdingding.modules.qd.entity.Studentproms;
import com.biostime.qdingding.modules.qd.entity.Transrecord;
import com.biostime.qdingding.modules.sys.entity.User;
import com.biostime.qdingding.modules.sys.utils.UserUtils;

/**
 * 合同Service
 * @author king
 * @version 2015-11-05
 */
@Service
@Transactional(readOnly = true)
public class ContractService extends CrudService<ContractDao, Contract> {
	
	@Autowired
	private ContractDao contractDao;
	@Autowired
	private TransrecordService transrecordService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private StudentService studentService ;
	@Autowired
	private MembercenterService memberCenterService;
	@Autowired
	private MemberstudentService memberstudentService;
    @Autowired
    private StudentpromsService studentpromsService;
    @Autowired 
    private PrivilegeService privilegeService;
    @Autowired
    private CenterService centerService;
	
	@Override
	public List<Contract> findList(Contract entity) {
		dataScopeFilter(entity, "dsf", "id=a.center_id", "id=a.create_by");
		
		return super.findList(entity);
	}
	
	/**
	 * 重写findPage方法 判定已支付的金额所达到的条件
	 */
	@Override
	public Page<Contract> findPage(Page<Contract> page, Contract entity) {
		entity.setPage(page);
		List<Contract> contractList = findList(entity);
		Transrecord transrecord = new Transrecord();
		for(Contract contract : contractList){
			transrecord.setContractId(Integer.valueOf(contract.getId()));
			transrecord.setType("0");
			transrecord.setInvalid(0);
			List<Transrecord> recordList = transrecordService.getContractRecord(transrecord);
			Double paidAmount = 0.0;
			for(Transrecord temp : recordList ){
				paidAmount += temp.getMoney();
			}
			if(paidAmount < (contract.getAmount()*0.3)){
				contract.setPayHint("请支付订金");
			}else if(paidAmount >= (contract.getAmount()*0.3) && paidAmount< contract.getAmount()){
				contract.setPayHint("已付订金");
			}else if(paidAmount >= contract.getAmount()){
				contract.setPayHint("已付全款");
			}
			contract.setPaidAmount(paidAmount);
		}
		page.setList(contractList);
		return page;
	}
	
	@Transactional
	public void save(Contract contract,HttpServletRequest request) {
		//当前用户
		User user = UserUtils.getUser();
		Center center = UserUtils.getCenter();
		center = centerService.get(center);
		//修改会员数据
		Member member = contract.getMember();
		member.setCenter(user.getCenter());
		if(member.getIsNewRecord()){
			member.setNikename(member.getName());
			member.setLoginFlag("0");
			member.setProviceId(Integer.parseInt(center.getProvince().getId()));
			member.setCityId(Integer.parseInt(center.getCity().getId()));
			member.setAreaId(Integer.parseInt(center.getArea().getId()));
		}
		memberService.save(member);
		
		//新建会员早教中心数据
		Membercenter memberCenter = new Membercenter();
		memberCenter.setCenter(user.getCenter());
		memberCenter.setMember(member);
		if(!memberCenterService.exist(memberCenter)){
			memberCenterService.save(memberCenter);
		}
		
		//修改学员数据
		Student student = contract.getStudent();
		student.setMobile(member.getMobile());
		student.setCenter(user.getCenter());
		
		if(student.getIsNewRecord() ){
			DecimalFormat dFormat = new DecimalFormat("0000");
			String code = "";
			Date nowDate = new Date();
			String nowDateString = DateUtils.formatDate(nowDate, "yyyyMMdd");
			
			String lastCode = getNowCode();
			if(StringUtils.isEmpty(lastCode)){
				code ="ST"+nowDateString+"0001";
			}else{
				int temp = Integer.valueOf(lastCode.substring(lastCode.length()-4, lastCode.length()));
				code = "ST"+nowDateString+dFormat.format(++temp);
			}
			student.setCode(code);
			student.setNikename("学员");
			student.setState(0);
			studentService.save(student);
		}
		
		//新建会员学员数据
		Memberstudent memberstudent =  new Memberstudent();
		memberstudent.setStudentId(Integer.valueOf(student.getId()));
		memberstudent.setMemberId(Integer.valueOf(member.getId()));
		if(!memberstudentService.exist(memberstudent)){
			memberstudentService.save(memberstudent);
		}
		
		//新建学员优惠数据
//		Studentproms studentproms = new Studentproms();
//		studentproms.setSetId(Integer.valueOf(contract.getSetId()));
//		studentproms.setStudentId(Integer.valueOf(student.getId()));
//		if(!studentpromsService.exist(studentproms)){
//			studentpromsService.save(studentproms);
//		}
		Studentproms studentproms = new Studentproms();
		studentproms.setStudentId(Integer.valueOf(student.getId()));
		studentpromsService.save(studentproms, request);
		
		contract.setCenter(user.getCenter()); //中心
		
		//新增
		if(contract.getIsNewRecord()){ 
			contract.setAbort(0);
			contract.setStatus(0);
			
			/**以前的合同都必须失效**/
			this.disable(contract); 
		}
		User sales = UserUtils.get(contract.getSales().getId());
		contract.setSales(sales);
		super.save(contract);

		//特权信息
		Privilege leavePriv = contract.getLeavePriv();
		leavePriv.setType("leave");
		leavePriv.setContractId(StringUtils.toInteger(contract.getId()));
		leavePriv.setStudentId(StringUtils.toInteger(student.getId()));
		if(leavePriv.getIsNewRecord()){
			leavePriv.setUsed(0);
		}
		privilegeService.save(leavePriv);
		
//		Privilege abortPriv = contract.getAbortPriv();
//		abortPriv.setType("abort");
//		abortPriv.setContractId(StringUtils.toInteger(contract.getId()));
//		abortPriv.setStudentId(StringUtils.toInteger(student.getId()));
//		if(abortPriv.getIsNewRecord()){
//			abortPriv.setUsed(0);
//		}
//		privilegeService.save(abortPriv);
		
		//更新学员所在中心
		Student stu = new Student();
		stu.setId(student.getId());
		stu.setCenter(user.getCenter());
		studentService.save(stu);
	}
	
	@Transactional
	private void disable(Contract contract) {
		dao.disable(contract);
	}

	@Transactional
	public  void create(Contract contract){
		User user = UserUtils.getUser();
		//修改会员数据
		Member member = contract.getMember();
		member.setCenter(user.getCenter());
		Member memberUpdate = memberService.get(member);
		if(memberUpdate==null){
			memberService.save(member);
		}else{
			memberUpdate.setName(member.getName());
			memberService.save(memberUpdate);
			member = memberService.getByMobile(memberUpdate.getMobile());
		}
		
		//新建会员早教中心数据
		Membercenter memberCenter = new Membercenter();
		memberCenter.setCenter(user.getCenter());
		memberCenter.setMember(member);
		if(memberCenterService.findList(memberCenter).size()==0){
			memberCenterService.save(memberCenter);
		}
		
		//修改学员数据
		Student student = contract.getStudent();
		student.setMobile(member.getMobile());
		Student studentUpdate = studentService.getfornm(student);
		if(studentUpdate==null){
			DecimalFormat dFormat = new DecimalFormat("0000");
			String code = "";
			Date nowDate = new Date();
			String nowDateString = DateUtils.formatDate(nowDate, "yyyyMMdd");
			
			String lastCode = getNowCode();
			if(StringUtils.isEmpty(lastCode)){
				code ="ST"+nowDateString+"0001";
			}else{
				int temp = Integer.valueOf(lastCode.substring(lastCode.length()-4, lastCode.length()));
				code = "ST"+nowDateString+dFormat.format(++temp);
			}
			student.setCenter(user.getCenter());
			student.setCode(code);
			studentService.save(student);
		}else{
			studentUpdate.setBirthday(student.getBirthday());
			studentUpdate.setName(student.getName());
			studentUpdate.setSex(student.getSex());
			studentService.save(studentUpdate);
			student = studentService.getfornm(studentUpdate);
		}
		
		//新建学员优惠数据
		Studentproms studentproms = new Studentproms();
		studentproms.setSetId(Integer.valueOf(contract.getSetId()));
		studentproms.setStudentId(Integer.valueOf(student.getId()));
		if(studentpromsService.getbySetIdStudentId(studentproms).size() < 1){
			studentpromsService.save(studentproms);
		}
		//新建会员学员数据
		Memberstudent memberstudent =  new Memberstudent();
		memberstudent.setStudentId(Integer.valueOf(student.getId()));
		memberstudent.setMemberId(Integer.valueOf(member.getId()));
		if(!memberstudentService.exist(memberstudent)){
			memberstudentService.save(memberstudent);
		}
		
		//新建合同
		if(contract.getCode() == null || contract.getCode() =="" || contract.getCode().equals("合同编号将自动生成")){
			
			DecimalFormat dFormat = new DecimalFormat("0000");
			String code = "";
			Date nowDate = new Date();
			String nowDateString = DateUtils.formatDate(nowDate, "yyyyMMdd");
			
			String lastCode = getNowCode();
			if(StringUtils.isEmpty(lastCode)){
				code ="CT"+nowDateString+"0001";
			}else{
				int temp = Integer.valueOf(lastCode.substring(lastCode.length()-4, lastCode.length()));
				code = "CT"+nowDateString+dFormat.format(++temp);
			}
			
			contract.setCode(code);
			contract.setCenter(user.getCenter());
			User sales = UserUtils.get(contract.getSales().getId());
			contract.setSales(sales);
			contract.setMember(member);
			contract.setStudent(student);
		}
		save(contract);
	}
	
	public Double getBalance(Contract contract){
		BalanceDto balanceDto = transrecordService.getBalance(contract.getStudent());
		double  balance = balanceDto.getSumPay() - balanceDto.getSumCost() - balanceDto.getSumFreeze();
		return balance;
	}
	
	/**
	 * 用于修改虚拟合同的保存
	 * 正常合同保存请用save();
	 */
	public void freeSave(Contract contract){
		dao.update(contract);
	}
	
	
	/**
	 * 查询学员ID是否绑定有生效的合同  如果有返回false 如果没有返回true
	 * @param contract
	 * @return
	 */
	public Integer isStudentStatus(Contract contract){
	    return contractDao.isStudentStatus(contract);
	}
	
	/**
	 * 通过学员ID获取合同
	 * @param studentId
	 * @return
	 */
	public Contract getByStudentId(int studentId) {
		return contractDao.getByStudentId(studentId);
	}
	
	/**
	 * 获取到最新插入的编号
	 * @param contract
	 * @return
	 */
	public String getNowCode(){
		Contract contract = contractDao.getNowCode();
		if(contract != null)
			return contract.getCode();
		
		return null;
	}
	
	/**
	 * 获取到最新插入的编号
	 * @param contract
	 * @return
	 */
	public String getLateCode(Contract contract){
		contract = contractDao.getLateCode(contract);
		if(contract != null && !StringUtils.isEmpty(contract.getCode())){
			return contract.getCode();
		}
		
		return null;
	}
	
	public Contract getByMobile(Contract contract){
		return dao.getByMobile(contract);
	}
	
	public Contract getByMobileStatus(Contract contract){
		return dao.getByMobileStatus(contract);
	}
	/**
	 * 
	 * @param id 宝宝id
	 * @return
	 */
	public int getByStudentIdStatus(String id){
		return dao.getByStudentIdStatus(id);
	}
	
//	<!-- ————————————————————————————楚河汉界，谁敢动我的，打死 ————————————————————————————————————-->
	public List<ContractDto> apiGetContract(String studentId){
		return contractDao.apiGetContract(studentId);
	}
	
	public List<ContractDto> apiGetHistoryContracts(String studentId){
		return contractDao.apiGetHistoryContracts(studentId);
	}

	public Student apiContractByMember(String userId){
		return contractDao.apiContractByMember(userId);
	}	
	
	public List<Student> apiContractByMember_version2(String userId){
		return contractDao.apiContractByMember_version2(userId);
	}
}
